package com.qf.service.impl;


import com.qf.constant.SsmModelConstant;
import com.qf.entity.User;
import com.qf.enums.ErrorMsgEnums;
import com.qf.exception.SsmModelException;
import com.qf.mapper.UserMapper;
import com.qf.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;



    //校验用户名
    @Override
    public void checkUsername(String username) {
        User user = new User();
        user.setUsername(username);
        int count = userMapper.selectCount(user);
        if (count!=0){
            log.info("【校验用户名】该用户名已被注册！ username={}",username);
            throw new SsmModelException(ErrorMsgEnums.USERNAME_UN_USABLE);
        }

    }

    //注册用户
    @Override
    @Transactional
    public void register(User user) {
        //生成盐
        String salt = UUID.randomUUID().toString();
        //加密&加盐
        String newPassword = new Md5Hash(user.getPassword(),salt,SsmModelConstant.MD5_NUM).toString();

        //封装数据
        user.setPassword(newPassword);
        user.setSalt(salt);

        int count = userMapper.insertSelective(user);
        if (count!=1){
            log.info("【用户注册】用户注册失败！ user={}",user);
            throw new SsmModelException(ErrorMsgEnums.USER_REGISTER_ERROR);
        }
    }

    //用户登录
    @Override
    public User login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        User oldUser = userMapper.selectOne(user);

        if (oldUser==null){
            log.info("【用户登录】用户名不存在 ！！ username={}",username);
            throw new SsmModelException(ErrorMsgEnums.LOGIN_USERNAME_ERROR);
        }

        String newPassword = new Md5Hash(password,oldUser.getSalt(), SsmModelConstant.MD5_NUM).toString();

        if (!oldUser.getPassword().equals(newPassword)){
            log.info("【用户登录】用户名或密码错误 ！！ username={},password={},user={}",username,password,oldUser);
            throw new SsmModelException(ErrorMsgEnums.LOGIN_PASSWORD_ERROR);
        }

        return oldUser;
    }


}
